package com.hourses.service.impl;

import com.hourses.mapper.OutStoreMapper;
import com.hourses.mapper.ProductMapper;
import com.hourses.page.Page;
import com.hourses.pojo.OutStore;
import com.hourses.pojo.Result;
import com.hourses.service.OutStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/5/8 13:51
 */
@Service
public class OutStoreServiceImpl implements OutStoreService {
    //添加出库单
    @Autowired
    private OutStoreMapper outStoreMapper;
    @Override
    public Result addOutStore(OutStore outStore) {
        Integer count = outStoreMapper.addOutStore(outStore);
        if (count>0){
            return Result.ok("添加出库单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加出库单失败！请联系管理员...");
    }

    //分页展示出库单
    @Override
    public Result selectOutListByPage(OutStore outStore, Page page) {
        //step1:先查询出满足查询条件的总行数
        Integer count = outStoreMapper.selectToTallNumOfOutStores(outStore);
        page.setTotalNum(count);
        //step2:再查询每一页需要展示的数据
        List<OutStore> outStores = outStoreMapper.selectPageList(outStore, page);
        page.setResultList(outStores);
        return Result.ok(page);
    }

    //最终确认出库
    @Autowired
    private ProductMapper productMapper;
    @Override
    @Transactional   //添加事务
    public Result endSureOutStore(OutStore outStore) {
        //step1:先判断product表中的库存还够不够
        Integer invent = productMapper.selectProductInventByproductId(outStore.getProductId());
        if (invent>outStore.getOutNum()){
            //库存够，则进行下一步操作
            //修改out_store表中的is_out字段为1
            Integer isOut = outStoreMapper.updateIsOut(outStore);
            if (isOut>0){
                //is_out字段修改成功
                //修改商品库存
                Integer res = outStoreMapper.updateProductInvent(outStore);
                if (res>0){
                    //库存修改成功，成功出库
                    return Result.ok("出库成功!");
                }
                //库存修改失败，出库失败
                return Result.err(Result.CODE_ERR_BUSINESS,"出库失败！请联系管理员...");
            }
            //is_out字段修改失败，不能出库
            return Result.err(Result.CODE_ERR_BUSINESS,"出库失败!请联系管理员...");
        }
        //库存不足，不进行出库
        return Result.err(Result.CODE_ERR_BUSINESS,"出库失败！库存不足...");
    }
}
